<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\video\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

use think\facade\Hook;

/**
 * 视频评论管理
 * @package app\video\admin
 */
class Commentartificial extends Admin
{
	/**
     * 预置评论
     * @author shiqiang
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function comment(){
		$data = $this->request->post('', null, 'trim');
		
		$play_id = $data['play_id'];
		$content = $data['content'];
		if($play_id == '' || $play_id < 1 || $content == ''){
			return '参数错误';
		}
		
		$rel = model('VideoPlayCommentArtificial', 'model') -> addData($play_id, $content);
		return $rel['data'];
	}
	
	/**
     * 预置评论列表
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function comment_list($play_id = []){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		$video_info = model('video/VideoPlay') -> getPlayFatherPlayInfo($play_id);
		$play_id = $video_info['data'];//关联的视频id
		
		$map = [];
		$map['play_id'] = $play_id;
		$list = model('VideoPlayCommentArtificial') -> where($map) -> paginate();
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('预置评论列表') // 设置页面标题
            ->setTableName('video_play_comment_artificial') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['content', '评论详情'],
                ['right_button', '操作', 'btn']
            ])
			->addTopButtons('delete') // 批量添加顶部按钮
			->addRightButton('delete') 
			->setRowList($list) // 设置表格数据,
            ->fetch(); // 渲染页面
    } 
	
	
/******************************************************** 管理员 - 预置操作 ******************************************************************/	
	private $user_id = [];
	private $map_mobile = [
			['mobile', '>=', 14490000001],
			['mobile', '<=', 14499999999]
		];
	/**
     * 可同步预置评论列表(管理员权限使用)
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function get_comment_list($create_time = '', $start_limit = '', $end_limit = ''){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
		$data_list = model('VideoPlayCommentArtificial') -> field('play_id') -> group('play_id') -> paginate();//获取视频id
		// 分页数据
        $page = $data_list->render();
		
		$rel_list = [];
		foreach($data_list as $key => $value){
			$play_id = $value -> play_id;
			$video_play = model('VideoPlay') -> find($play_id);
			if(!empty($video_play) && $video_play['play_operation_status'] == 1 && $video_play['play_status'] == 1){
				$rel_list[$key] 							= $video_play;
				$rel_list[$key]['file_size']                = formatBytes($video_play['file_size']);
				$rel_list[$key]['play_operation_status']    = $video_play['play_operation_status'];
				$rel_list[$key]['author']                   = $video_play['get_uc_member']['nick_name'];
				$rel_list[$key]['count']                   =  model('VideoPlayCommentArtificial') -> where('play_id', $play_id) -> count();
			}
		}
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post();
			$play_id 		= isset($data['ids']) ? $data['ids'] : [];
			$create_time 	= isset($data['create_time']) ? $data['create_time'] : '';
			$start_limit 	= intval(isset($data['start_limit']) ? $data['start_limit'] : 0);
			$end_limit 		= intval(isset($data['end_limit']) ? $data['end_limit'] : 0);
			
			$post_token = isset($data['TOKEN']) ? $data['TOKEN'] : '';
			if(!form_check_token($post_token)){//验证重复提交
				 $this->error('请不要重复提交页面');
			}
			
			$datetime = date('Y-m-d');
			if($create_time > $datetime){
				$this->error('更新日期不能超过今天');
			}
			
			// $user_id = model('user_center/UcMemberMobile', 'model\user') -> where($this -> map_mobile) -> column('uid');//获取 预置用户号段 uid
			$user_id = datacache('VideoPlayCommentartificial', 'datacache') ->  getPushUserMoblie();
			if(!empty($user_id)){
				$this -> user_id = $user_id;
				$this -> get_comment_play($play_id, strtotime($create_time), $start_limit, $end_limit);//同步预置评论
				$this->success('推送成功' ,'get_comment_list?create_time='.$create_time.'&start_limit='.$start_limit.'&end_limit='.$end_limit);
			}
		}
		form_create_token();//创建表单token
		$token = session('TOKEN');
		
		$top_html = <<<EOF
				<form action="get_comment_list" class="form-horizontal row" enctype="multipart/form-data" method="post">
					<div class="col-md-6 push">
						<div class="input-group">
							<span class="input-group-addon">推送初始时间</span>
	<input class="js-datepicker form-control" type="text" id="create_time" name="create_time" value="{$create_time}" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd">
							<span class="input-group-addon">推送条数</span>
	<input class="form-control" type="number" id="start_limit" name="start_limit" value="{$start_limit}" placeholder="0" >
	<span class="input-group-addon">至</span>
	<input class="form-control" type="number" id="end_limit" name="end_limit" value="{$end_limit}" placeholder="1000" >
						</div>
					</div>
					<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">
						<button class="btn btn-sm btn-primary" type="submit"> 开始推送</button>
						<a href="get_comment_list/" class="btn btn-sm btn-default" type="reset"><i class="fa fa-reply"></i> 重置</a>
						<input type="hidden" name="TOKEN" value="{$token}" />
					</div>
				
EOF;

		$bottom_html = <<<EOF
		</form>
EOF;

		$js = <<<EOF
		<script>
			jQuery(function () {
				App.initHelpers(['appear', 'slimscroll', 'magnific-popup', 'table-tools']);
						App.initHelpers(["datepicker"]);
					});
		</script>
EOF;
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('可同步视频列表') // 设置页面标题
            ->setTableName('video_play_comment_artificial') // 设置数据表名
            ->addColumns([ // 批量添加列
				['id', '视频id'],
                ['author', '上传作者', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['main_title', '视频标题'],
                ['play_type', '视频类型', 'status', '', [1 => '短视频:default', 2 => '长视频:danger']],
                ['play_operation_status', '人审状态', 'status', '', [0 => '待审核:default', 1 => '正常:success', 2 => '已屏蔽:danger', 3 => '上传中:danger']],
                ['count', '预置评论数量'],
                ['create_time', '创建时间', 'datetime'],
            ])
			->setExtraHtml($top_html, 'toolbar_top')
			->setExtraHtml($bottom_html, 'table_bottom')
			->css('libs/bootstrap-datepicker/bootstrap-datepicker3')
			->js('libs/bootstrap-datepicker/bootstrap-datepicker')
			->js('libs/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min')
			->setExtraJs($js)
			->setPages($page) // 设置分页数据
			->setRowList($rel_list) // 设置表格数据,
            ->fetch(); // 渲染页面
    }
	
	/**
     * 查询需要推送的视频ID (推送评论)
     * @author shiqiang <976162041@qq.com>
	 * @param  array $play_id  视频id
	 * @param  string $create_time  评论开始时间
	 * @param  int $limit  处理条数
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	private function get_comment_play($play_id = [], $create_time = '', $start_limit = 0, $end_limit = 1000){
		$map = [];
		if(!empty($play_id)){
			$map['play_id'] = $play_id;
		}
		$play_list = model('VideoPlayCommentArtificial') -> field('play_id') -> where($map) -> group('play_id') -> select() -> toArray();//获取视频id
		if(!empty($play_list)){
			foreach($play_list as $key => $value){
				$play_time = datacache('VideoPlayCommentartificial', 'datacache') -> getPushPlayCreateTimePlayId($value['play_id']);
				if($play_time == '') continue;
				if($create_time == '' || $create_time < $play_time){//更新时间不能大于 视频上传时间
					$create_time = $play_time;
				}
				$push_limit = mt_rand($start_limit, $end_limit);
				$this -> pust_comment($value['play_id'], $create_time, $push_limit);
			}
		}
	} 
	
	/**
     * 推送评论
     * @author shiqiang <976162041@qq.com>
	 * @param  int $play_id  视频id
	 * @param  string $create_time  评论开始时间
	 * @param  int $limit  处理条数
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	private function pust_comment($play_id, $create_time, $push_limit = 1000){
		$user_id = $this -> user_id;
		$map = [];
		$map['play_id'] = $play_id;
		$comment_list = model('VideoPlayCommentArtificial') -> where($map) -> limit($push_limit) -> select();//获取视频id
		if(!empty($comment_list)){
			foreach($comment_list as $value){
				$rand 			= mt_rand(0, (count($user_id) - 1));
				$uid 			= $user_id[$rand];
				$comment_time 	= mt_rand($create_time, time());
				
				// $rel = model('VideoPlayComment') -> addDataTimes($uid, $play_id, $value['content'], $comment_time);
				$rel = controller('Videologic', 'logic') -> add_comment($uid, $play_id, $value['content'], $comment_time);//预置评论推送
				if($rel['code'] == 200){
					model('VideoPlayCommentArtificial') -> destroy($value['id']);//清掉预置评论
				}
			}
		}
	}
	
	
	/**
     * 预置视频列表
     * @author shiqiang <976162041@qq.com>
	 * @param  int $play_id  视频id
	 * @param  string $create_time  评论开始时间
	 * @param  int $limit  处理条数
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	public function get_push_play_support(){
		// 获取筛选
        $map = $this->getMap();//dump($map);die;
        // 数据列表
		$map[] = ['play_status', '=', 1];
		$map[] = ['play_operation_status', '=', 1];
        $data_list = model('VideoPlay', 'model') -> where($map) -> order('support_times desc, create_time desc') -> paginate();//dump($data_list);die;
        // 分页数据
        $page = $data_list->render();
		
		// 批量点赞
        $btn_batch_support = [
			'title' => '批量点赞',
			'class' => 'btn btn-primary js-get',
            'href'  => url('add_push_batch_support',['play_id' => '__id__'])
        ];
		
        $btn_support = [
            'title' => '点赞',
            'icon'  => 'fa fa-fw fa-bookmark',
            'href'  => url('add_push_support',['play_id' => '__id__'])
        ];
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
        $rel_list =[];
        foreach ($data_list as $key => $value) {
            $rel_list[$key] = $value->toArray();
            $rel_list[$key]['file_size']                = formatBytes($value['file_size']);
            $rel_list[$key]['play_operation_status']    = $value['play_operation_status'];
            $rel_list[$key]['author']                   = $value['get_uc_member']['nick_name'];
        } //dump($rel_list);die;
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('视频管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('video_play') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['author', '上传作者', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['main_title', '视频标题'],
                ['play_type', '视频类型', 'status', '', [1 => '短视频:default', 2 => '长视频:danger']],
                ['play_operation_status', '人审状态', 'status', '', [0 => '待审核:default', 1 => '正常:success', 2 => '已屏蔽:danger', 3 => '上传中:danger']],
                ['support_times', '点赞数量'],
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->addTopButton('custom', $btn_batch_support, true) // 批量添加顶部按钮
			->addRightButton('custom', $btn_support, ['area' => ['50%', '70%']]) // 添加授权按钮
            ->setPages($page) // 设置分页数据
            ->setRowList($rel_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}
	
	/**
     * 预置批量视频点赞
     * @author shiqiang <976162041@qq.com>
	 * @param  array $play_id  视频id
	 * @param  int $support_num  点赞数量
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	public function add_push_batch_support($ids = []){
		$user_id = datacache('VideoPlayCommentartificial', 'datacache') ->  getPushUserMoblie();
		$support_num 	= count($user_id);
		
		// 保存数据
		if ($this->request->isPost()) {
			//运行超时
			ini_set('max_execution_time', '0');
			//数据接收
			$data = $this->request->post();
			$start_limit 	= intval(isset($data['start_limit']) ? $data['start_limit'] : 0);
			$end_limit 		= intval(isset($data['end_limit']) ? $data['end_limit'] : 0);
			if($ids == '' || $start_limit == '' || $start_limit == 0 || $end_limit == '' || $end_limit == 0){
				$this->error('数据格式错误');
			}
			$play_id = explode(',', $ids);
			$user_arr = [];
			foreach($play_id as $value){
				$play_time 	= model('VideoPlay') -> cache(true) -> find($value) -> create_time;
				$rand_num 	= mt_rand($start_limit, $end_limit);//随机点赞数
				$user_arr 	= array_rand_tt($user_id, $rand_num);//随机从用户中拿出一批用户
				
				foreach($user_arr as $user_key){
					$create_time = mt_rand($play_time, time());
					$res = controller('Videologic', 'logic') -> add_support($user_id[$user_key], $value, $create_time);//点赞
				}
			}
			$this->success('点赞成功', null, '_parent_reload');
		}
		// 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('视频预置点赞')
			->addNumber('start_limit', '最少点赞数')
			->addNumber('end_limit', '最大点赞数', '当前可点赞最大数量：<span style="color:red">' . $support_num ."</span> (此数量包含已经点过赞的用户)")
            ->fetch();
	}
	
	/**
     * 预置视频点赞
     * @author shiqiang <976162041@qq.com>
	 * @param  int $play_id  视频id
	 * @param  int $support_num  点赞数量
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	public function add_push_support($play_id = ''){
		$user_id 		= datacache('VideoPlayCommentartificial', 'datacache') ->  getPushUserMoblie();
		$support_num 	= count($user_id);
		
		// 保存数据
		if ($this->request->isPost()) {
			 //运行超时
			ini_set('max_execution_time', '0');
			//数据接收
			$data = $this->request->post();
			$start_limit 	= intval(isset($data['start_limit']) ? $data['start_limit'] : 0);
			$end_limit 		= intval(isset($data['end_limit']) ? $data['end_limit'] : 0);
			if($play_id == '' || $play_id == 0 || $start_limit == '' || $start_limit == 0 || $end_limit == '' || $end_limit == 0){
				$this->error('数据格式错误');
			}
			
			$rand_num 	= mt_rand($start_limit, $end_limit);//随机点赞数
			$user_arr 	= array_rand_tt($user_id, $rand_num);//随机从用户中拿出一批用户
			
			$play_time = model('VideoPlay') -> cache(true) -> find($play_id) -> create_time;
			foreach($user_arr as $user_key){
				$create_time = mt_rand($play_time, time());
				$res = controller('Videologic', 'logic') -> add_support($user_id[$user_key], $play_id, $create_time);//点赞
			}
			$this->success('点赞成功', null, '_parent_reload');
		}
		
		// 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('视频预置点赞')
			->addNumber('start_limit', '最少点赞数')
			->addNumber('end_limit', '最大点赞数', '当前可点赞最大数量：<span style="color:red">' . $support_num ."</span> (此数量包含已经点过赞的用户)")
            ->fetch();
	}
	
	
	/**
     * 生成预置用户
     * @author shiqiang
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
	public function get_push_play_user($date1 = '', $date2 = '', $user_count = ''){

		$date	= date('Y-m-d');
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post();
			
			$post_token = isset($data['TOKEN']) ? $data['TOKEN'] : '';
			if(!form_check_token($post_token)){//验证重复提交
				 $this->error('请不要重复提交页面');
			}
			
			$date1 	= isset($data['date1']) ? $data['date1'] : date('Y-m-d 00:00:00');
			$date2 	= isset($data['date2']) ? $data['date2'] : date('Y-m-d 23:59:59');
			
			$user_count = intval(isset($data['user_count']) ? $data['user_count'] : 0);
			if($date2 > $date || $user_count == ''){
				$this->error('数据格式错误');
			}
			$start_date = strtotime($date1);
			$end_date 	= $date2 == $date ? time() : strtotime($date2 . '23:59:59');
			
			$user_rand = $this -> unique_rand(14490000001, 14499999999, $user_count);
			$user_id = [];
			foreach($user_rand as $value){
				$mobile = $value;
				$create_time = mt_rand($start_date, $end_date);
				$user_info = controller('user_center/Userlogic',"logic\user") -> login_mobile($mobile, 5959, 0, $create_time);//注册用户获取uid
			}
			datacache('VideoPlayCommentartificial', 'datacache') ->  getPushUserMoblie(true);//更新缓存
			$this->success('生成成功');
		}
		
		$data_list = model('user_center/UcMemberMobile', 'model\user') -> where($this -> map_mobile) -> order('id desc') -> paginate();
		$rel_list = [];
		foreach($data_list as $key => $value){
			$rel_list[$key] = $value->toArray();
			$rel_list[$key]['nick_name'] 	= $value['get_uc_member']['nick_name'];
			$rel_list[$key]['sex'] 			= $value['get_uc_member']['sex'];
			$rel_list[$key]['birthday'] 	= substr($value['get_uc_member']['birthday'],0, 10);
		}
		// 分页数据
        $page = $data_list->render();
		
		form_create_token();//创建表单token
		$token = session('TOKEN');
		
		$top_html = <<<EOF
				<form action="get_push_play_user" class="form-horizontal row" enctype="multipart/form-data" method="post">
					<div class="col-md-5 push">
						<div class="input-group">
							<span class="input-group-addon">生成时间段</span>
							<div class="input-daterange input-group" data-date-format="yyyy-mm-dd" data-start-date="" data-end-date="{$date}" >
								<input class="form-control" type="text" id="date1" name="date1" value="{$date1}" placeholder="yyyy-mm-dd" />
								<span class="input-group-addon"><i class="fa fa-chevron-right"></i></span>
								<input class="form-control" type="text" id="date2" name="date2" value="{$date2}" placeholder="yyyy-mm-dd" />
							</div>
							
							<span class="input-group-addon">生成人数</span>
	<input class="form-control" type="number" id="user_count" name="user_count" value="{$user_count}" placeholder="0" >
						</div>
					</div>
					<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">
						<button class="btn btn-sm btn-primary" type="submit"> 开始推送</button>
						<a href="get_push_play_user/" class="btn btn-sm btn-default" type="reset"><i class="fa fa-reply"></i> 重置</a>
						<input type="hidden" name="TOKEN" value="{$token}" />
					</div>
				
EOF;

		$bottom_html = <<<EOF
		</form>
EOF;

		$js = <<<EOF
		<script>
			jQuery(function () {
				App.initHelpers(['appear', 'slimscroll', 'magnific-popup', 'table-tools']);
						App.initHelpers(["datepicker"]);
					});
		</script>
EOF;

		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('预置用户列表') // 设置页面标题
            ->setTableName('uc_member_mobile') // 设置数据表名
            ->addColumns([ // 批量添加列
				['uid', '用户id'],
				['nick_name', '昵称'],
                ['mobile', '手机号'],
                ['sex', '性别', ['不显示' ,'男' ,'女']],
                ['birthday', '生日'],
				['create_time', '生成时间', 'datetime'],
            ])
			->setExtraHtml($top_html, 'toolbar_top')
			->setExtraHtml($bottom_html, 'table_bottom')
			->css('libs/bootstrap-datepicker/bootstrap-datepicker3')
			->js('libs/bootstrap-datepicker/bootstrap-datepicker')
			->js('libs/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min')
			->setExtraJs($js)
			->setPages($page) // 设置分页数据
			->setRowList($rel_list) // 设置表格数据,
            ->fetch(); // 渲染页面
	}
	
	/*
	 * array unique_rand( int $min, int $max, int $num )
	 * 生成一定数量的不重复随机数
	 * $min 和 $max: 指定随机数的范围
	 * $num: 指定生成数量
	 */
	 
	private function unique_rand($min,$max,$num){
		$count = 0;
		$return_arr = array();
		while($count < $num){
			$return_arr[] = mt_rand($min,$max);
			$return_arr = array_flip(array_flip($return_arr));
			$count = count($return_arr);
		}
		shuffle($return_arr);
		return $return_arr;
	}
}
